$(function () {
    // 初始化出生日期选择器
    initBirthDateSelect();
    // 全选功能
    $('#selectAll').change(function () {
        const isChecked = $(this).prop('checked');
        $('input[name="idType"]').prop('checked', isChecked);
        updateIdNumberForms();
    });
    // 单个证件类型选择
    $('input[name="idType"]').change(function () {
        updateSelectAllState();
        updateIdNumberForms();
    });
    // 初始调用一次更新表单
    updateIdNumberForms();
});

// 更新全选状态
function updateSelectAllState() {
    const totalCheckboxes = $('input[name="idType"]').length;
    const checkedCheckboxes = $('input[name="idType"]:checked').length;
    $('#selectAll').prop('checked', totalCheckboxes === checkedCheckboxes);
}

// 初始化出生日期选择器
function initBirthDateSelect() {
    const $yearSelect = $('.year-select');
    const $monthSelect = $('.month-select');
    const $daySelect = $('.day-select');
    const today = new Date();
    const currentYear = today.getFullYear();
    const maxYear = currentYear;
    const minYear = currentYear - 100;
    // 填充年份选项
    for (let year = maxYear; year >= minYear; year--) {
        $yearSelect.append(
            $('<option>', {
                value: year,
                text: year + '年'
            })
        );
    }
    // 填充月份选项
    for (let month = 1; month <= 12; month++) {
        $monthSelect.append(
            $('<option>', {
                value: month,
                text: month + '月'
            })
        );
    }
    // 初始更新天数
    updateDays($yearSelect, $monthSelect, $daySelect);
    // 绑定change事件
    $yearSelect.on('change', function() {
        updateDays($yearSelect, $monthSelect, $daySelect);
    });
    $monthSelect.on('change', function() {
        updateDays($yearSelect, $monthSelect, $daySelect);
    });
}

// 更新天数选择器
function updateDays($yearSelect, $monthSelect, $daySelect) {
    const year = parseInt($yearSelect.val());
    const month = parseInt($monthSelect.val());
    const daysInMonth = new Date(year, month, 0).getDate();
    $daySelect.empty();
    for (let day = 1; day <= daysInMonth; day++) {
        $daySelect.append(
            $('<option>', {
                value: day,
                text: day + '日'
            })
        );
    }
}

// 更新证件号码输入表单
function updateIdNumberForms() {
    const $formsContainer = $('#idNumberForms');
    $formsContainer.empty();
    $('input[name="idType"]:checked').each(function () {
        const idType = $(this).val();
        const formHtml = createIdNumberForm(idType);
        $formsContainer.append(formHtml);
    });
    // 为护照表单绑定事件
    bindPassportEvents();
}

// 创建证件号码输入表单
function createIdNumberForm(idType) {
    const $form = $('<div>', {
        class: 'form-group id-number-form'
    });
    const $inputGroup = $('<div>', {
        class: 'input-group'
    }).append(
        $('<label>').text(idType + '号码：'),
        $('<input>', {
            type: 'text',
            class: 'form-input',
            name: 'idNumber_' + idType,
            placeholder: '请输入' + idType + '号码'
        }),
        $('<div>', {
            class: 'error-message'
        })
    );
    $form.append($inputGroup);
    // 如果是护照，添加有效期输入
    if (idType === '护照') {
        const $expiryGroup = createPassportExpiryGroup();
        $form.append($expiryGroup);
    }
    return $form;
}

// 创建护照有效期输入组
function createPassportExpiryGroup() {
    const $group = $('<div>', {
        class: 'passport-expiry'
    });
    const $dateSelect = $('<div>', {
        class: 'expiry-date-select'
    }).append(
        $('<label>').text('有效期：'),
        createYearSelect('passport_year'),
        createMonthSelect('passport_month'),
        createDaySelect('passport_day')
    );
    const $lifetimeLabel = $('<label>', {
        class: 'lifetime-label'
    }).append(
        $('<input>', {
            type: 'checkbox',
            name: 'passport_lifetime',
            class: 'lifetime-checkbox'
        }),
        $('<span>').text('终生有效')
    );
    return $group.append($dateSelect, $lifetimeLabel);
}

// 创建年份选择器
function createYearSelect(name) {
    const $select = $('<select>', {
        name: name
    });
    const currentYear = new Date().getFullYear();
    for (let i = 0; i <= 50; i++) {
        const year = currentYear + i;
        $select.append(
            $('<option>', {
                value: year,
                text: year + '年'
            })
        );
    }
    return $select;
}

// 创建月份选择器
function createMonthSelect(name) {
    const $select = $('<select>', {
        name: name
    });
    for (let i = 1; i <= 12; i++) {
        $select.append(
            $('<option>', {
                value: i,
                text: i + '月'
            })
        );
    }
    return $select;
}

// 创建日期选择器
function createDaySelect(name) {
    const $select = $('<select>', {
        name: name
    });
    for (let i = 1; i <= 31; i++) {
        $select.append(
            $('<option>', {
                value: i,
                text: i + '日'
            })
        );
    }
    return $select;
}

// 绑定护照相关事件
function bindPassportEvents() {
    $('.lifetime-checkbox').on('change', function() {
        const $dateSelects = $(this).closest('.passport-expiry').find('select');
        $dateSelects.prop('disabled', $(this).is(':checked'));
    });
    // 绑定护照有效期日期联动
    $('.passport-expiry select[name="passport_year"], .passport-expiry select[name="passport_month"]').on('change', function() {
        const $container = $(this).closest('.passport-expiry');
        const year = parseInt($container.find('select[name="passport_year"]').val());
        const month = parseInt($container.find('select[name="passport_month"]').val());
        const $daySelect = $container.find('select[name="passport_day"]');

        updatePassportDays(year, month, $daySelect);
    });
}

// 更新护照有效期的天数
function updatePassportDays(year, month, $daySelect) {
    const daysInMonth = new Date(year, month, 0).getDate();
    const currentDay = $daySelect.val();
    $daySelect.empty();
    for (let i = 1; i <= daysInMonth; i++) {
        $daySelect.append(
            $('<option>', {
                value: i,
                text: i + '日'
            })
        );
    }
    // 尽量保持原来选择的日期
    if (currentDay && currentDay <= daysInMonth) {
        $daySelect.val(currentDay);
    }
}

// 表单验证
function validateForm() {
    let isValid = true;
    $('.error-message').hide();
    $('.form-input').removeClass('error');
    // 验证中文名或英文名至少填一项
    const chineseName = $('[name="chineseName"]').val().trim();
    const surname = $('[name="surname"]').val().trim();
    const givenName = $('[name="givenName"]').val().trim();

    if (!chineseName && (!surname || !givenName)) {
        isValid = false;
        if (!chineseName) {
            $('[name="chineseName"]').addClass('error')
                .siblings('.error-message')
                .text('请输入中文姓名').show();
        }
        if (!surname || !givenName) {
            $('.eng-name-inputs').siblings('.error-message')
                .text('请完整输入英文姓名').show();
            if (!surname) $('[name="surname"]').addClass('error');
            if (!givenName) $('[name="givenName"]').addClass('error');
        }
    }
    // 验证国籍
    const nationality = $('[name="nationality"]').val().trim();
    if (!nationality) {
        isValid = false;
        $('[name="nationality"]').addClass('error')
            .siblings('.error-message')
            .text('请输入国籍').show();
    }
    // 验证证件类型和号码
    const $checkedIdTypes = $('input[name="idType"]:checked');
    if ($checkedIdTypes.length === 0) {
        isValid = false;
        $('#idTypeGroup').siblings('.error-message')
            .text('请至少选择一种证件类型').show();
    } else {
        $checkedIdTypes.each(function() {
            const idType = $(this).val();
            const $idNumber = $('[name="idNumber_' + idType + '"]');
            if (!$idNumber.val().trim()) {
                isValid = false;
                $idNumber.addClass('error')
                    .closest('.input-group')
                    .find('.error-message')
                    .text('请输入' + idType + '号码').show();
            }
        });
    }
    return isValid;
}

// 提交表单
function submitForm() {
    if (!validateForm()) {
        return;
    }
    // 构建证件信息数组
    const documents = [];
    $('input[name="idType"]:checked').each(function() {
        const idType = $(this).val();
        const doc = {
            document_type: idType,
            document_number: $('[name="idNumber_' + idType + '"]').val().trim()
        };

        // 处理护照有效期
        if (idType === '护照') {
            const isLifetime = $('[name="passport_lifetime"]').is(':checked');
            if (isLifetime) {
                doc.expiry_date = "终生有效";
            } else {
                const year = $('[name="passport_year"]').val();
                const month = String($('[name="passport_month"]').val()).padStart(2, '0');
                const day = String($('[name="passport_day"]').val()).padStart(2, '0');
                doc.expiry_date = `${year}-${month}-${day}`;
            }
        }

        documents.push(doc);
    });
    // 构建普通的对象数据
    const formData = {
        chineseName: $('[name="chineseName"]').val().trim(),
        surname: $('[name="surname"]').val().trim(),
        givenName: $('[name="givenName"]').val().trim(),
        gender: $('[name="gender"]:checked').val(),
        nationality: $('[name="nationality"]').val().trim(),
        birthYear: $('.year-select').val(),
        birthMonth: String($('.month-select').val()).padStart(2, '0'),
        birthDay: String($('.day-select').val()).padStart(2, '0'),
        phone: $('[name="phone"]').val().trim(),
        email: $('[name="email"]').val().trim(),
        isDefault: $('[name="defaultTraveler"]').is(':checked'),
        documents: documents
    };
    // 发送到服务器
    $.ajax({
        url: 'addTraveler',
        type: 'POST',
        contentType: 'application/json', // 设置内容类型为 JSON
        data: JSON.stringify(formData), // 将数据转换为 JSON 字符串
        dataType: 'json',
        success: function(data) {
            if (data.flag) {
                alert(data.message);
                history.back();
            } else {
                alert(data.message || '保存失败');
            }
        }
    });
}
